import grp
import subprocess
import time

class ConfigureGroups:
    def __init__(self, groups):
        self.groups = groups
        self.successful = 0
        self.failed     = 0
        self.oo_sync    = 0

    def configure(self):
        """
        Configure group resources.
        """
        print "\033[1;36m- Configuring Groups\033[1;m"
        runtime_start = time.time()
        groups = self.groups

        for group in groups:
            # Convert gid into int for comparsion
            new_gid = int(groups[group]['gid'])
            # Check if the groups aready exist
            try:
                group_info = grp.getgrnam(group)
                # Do the gid's match
                old_gid = group_info[2]
                if old_gid == new_gid:
                    self.successful += 1
                else:
                    print "%s has wrong gid: %s, changing to %s" % (group, old_gid, new_gid)
                    # Convert gid to string for subprocess call.
                    subprocess.call(['/usr/sbin/groupmod', group, '-g', str(new_gid)])
                    self.successful += 1
                    self.oo_sync += 1
            except KeyError:
                print "%s does not exist...creating" % group
                subprocess.call(['/usr/sbin/groupadd', group, '-g', str(new_gid)])
                self.successful += 1
                self.oo_sync += 1

        # Collect Stats
        runtime_end = time.time()
        runtime = (runtime_end - runtime_start)

        stats = {
            'runtime'   : runtime,
            'successful': self.successful,
            'failed'    : self.failed,
            'oo_sync'   : self.oo_sync
        }

        return stats
